package com.ctos.ojcodesandbox.controller;

import cn.hutool.http.server.HttpServerRequest;
import cn.hutool.http.server.HttpServerResponse;
import com.ctos.ojcodesandbox.JavaDockerCodeSandbox;
import com.ctos.ojcodesandbox.model.ExecuteCodeRequest;
import com.ctos.ojcodesandbox.model.ExecuteCodeResponse;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController("/")
public class MainController {
    @Resource
    JavaDockerCodeSandbox sandbox;

    private static final String AUTH_HEADER = "AUTH";

    private static final String AUTH_SECRET = "ctos";

    @PostMapping("/executeCode")
    public ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest
            , HttpServletRequest request
            , HttpServletResponse response){
        if (executeCodeRequest == null){
            return null;
        }
        if (!AUTH_SECRET.equals(request.getHeader(AUTH_HEADER))){
            response.setStatus(403);
            return null;
        }
        ExecuteCodeResponse executeCodeResponse = sandbox.executeCode(executeCodeRequest);
        if (executeCodeResponse ==null){
            return new ExecuteCodeResponse(null,"error",500, null);
        }
        return executeCodeResponse;
    }
}
